package com.anywhere.freightman.system.controller;

import com.anywhere.freightman.common.entity.FileEntity;
import com.anywhere.freightman.common.entity.ReturnResp;
import com.anywhere.freightman.system.service.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("file")
@Api(tags = "文件上传")
public class FileController {

    @Autowired
    private IFileService fileService;

    @PostMapping
    @ApiOperation("上传文件")
    public ReturnResp uploadImg(@RequestParam("file") MultipartFile file) {
        return ReturnResp.buildOk(fileService.upload(file));
    }

    @DeleteMapping("/delete/{id}")
    public ReturnResp delete(@PathVariable("id") long id) {
        // 第一种删除：参数：完整地址
        fileService.delete(id);
        return ReturnResp.buildOk();
    }

    @GetMapping("view/{fileId}")
    @ApiOperation("文件预览")
    public void viewFile(@PathVariable("fileId") Long fileId,
                         HttpServletResponse response) throws IOException {
        FileEntity entity = fileService.downloadFile(fileId);
        convertResp(entity.getBytes(), entity.getFileName(), response);
    }

    @GetMapping("image/{fileId}")
    @ApiOperation("图片预览")
    public void viewImageFile(@PathVariable("fileId") Long fileId,
                              HttpServletResponse response) throws IOException {
        FileEntity entity = fileService.downloadFile(fileId);
        response.reset();
        response.setContentType("image/jpeg");
        ServletOutputStream out = response.getOutputStream();
        out.write(entity.getBytes());
        out.close();
    }

    @GetMapping
    public void downloadFile(@RequestParam("groupName") String groupName,
                             @RequestParam("path") String path,
                             @RequestParam("fileName") String fileName,
                             HttpServletResponse response) throws IOException {
        byte[] bytes = fileService.downloadFile(groupName, path);
        convertResp(bytes, fileName, response);
    }

    private void convertResp(byte[] bytes, String fileName, HttpServletResponse response) throws IOException {
        //设置相应类型application/octet-stream
        response.reset();
        response.setContentType("application/octet-stream");
        //设置头信息                 Content-Disposition为属性名  附件形式打开下载文件   指定名称  为 设定的fileName
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 写入到流
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();
    }


}
